<template>
  <div>
    <n-card title="活动列表">
      <template #header-extra>
        <n-space>
          <n-select
            v-model:value="filters.status"
            placeholder="活动状态"
            :options="statusOptions"
            clearable
            style="width: 150px"
            @update:value="loadActivities"
          />
          <n-select
            v-model:value="filters.category"
            placeholder="活动类别"
            :options="categoryOptions"
            clearable
            style="width: 150px"
            @update:value="loadActivities"
          />
        </n-space>
      </template>

      <n-space vertical size="large">
        <n-list hoverable>
          <n-list-item v-for="activity in activities" :key="activity.id">
            <n-thing>
              <template #avatar>
                <n-avatar>
                  <n-icon><CalendarOutline /></n-icon>
                </n-avatar>
              </template>
              <template #header>
                <n-space align="center">
                  <span @click="router.push(`/activity/detail/${activity.id}`)" style="cursor: pointer;">
                    {{ activity.title }}
                  </span>
                  <n-tag v-if="activity.status === 'RECRUITING'" type="success" size="small">报名中</n-tag>
                  <n-tag v-else-if="activity.status === 'IN_PROGRESS'" type="info" size="small">进行中</n-tag>
                  <n-tag v-else-if="activity.status === 'COMPLETED'" type="default" size="small">已完成</n-tag>
                  <n-tag v-else type="warning" size="small">{{ activity.status }}</n-tag>
                </n-space>
              </template>
              <template #description>
                <n-space size="small">
                  <n-text depth="3">
                    <n-icon><LocationOutline /></n-icon>
                    {{ activity.location }}
                  </n-text>
                  <n-text depth="3">
                    <n-icon><TimeOutline /></n-icon>
                    {{ formatDate(activity.startTime) }}
                  </n-text>
                  <n-text depth="3">
                    <n-icon><PeopleOutline /></n-icon>
                    {{ activity.currentParticipants }}/{{ activity.maxParticipants || '不限' }}
                  </n-text>
                  <n-text depth="3">
                    <n-icon><TrophyOutline /></n-icon>
                    {{ activity.pointsReward }}积分
                  </n-text>
                </n-space>
              </template>
              {{ activity.description }}
              <template #action>
                <n-space>
                  <n-button size="small" @click="router.push(`/activity/detail/${activity.id}`)">
                    查看详情
                  </n-button>
                  <n-button
                    v-if="activity.status === 'RECRUITING'"
                    type="primary"
                    size="small"
                    @click="handleEnroll(activity)"
                  >
                    立即报名
                  </n-button>
                </n-space>
              </template>
            </n-thing>
          </n-list-item>
        </n-list>

        <n-pagination
          v-model:page="pagination.page"
          :page-count="pagination.pageCount"
          :page-size="pagination.pageSize"
          show-size-picker
          :page-sizes="[10, 20, 30, 40]"
          @update:page="loadActivities"
          @update:page-size="handlePageSizeChange"
        />
      </n-space>
    </n-card>

    <n-modal v-model:show="enrollModalVisible" preset="dialog" title="报名活动">
      <n-form :model="enrollForm">
        <n-form-item label="报名理由">
          <n-input
            v-model:value="enrollForm.reason"
            type="textarea"
            placeholder="请简要说明您的报名理由"
            :rows="4"
          />
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="enrollModalVisible = false">取消</n-button>
          <n-button type="primary" @click="confirmEnroll">确认报名</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getActivityList, enrollActivity } from '@/api/activity'
import { CalendarOutline, LocationOutline, TimeOutline, PeopleOutline, TrophyOutline } from '@vicons/ionicons5'

const router = useRouter()
const userStore = useUserStore()

const activities = ref([])
const filters = reactive({
  status: null,
  category: null
})
const pagination = reactive({
  page: 1,
  pageSize: 10,
  pageCount: 1
})

const enrollModalVisible = ref(false)
const enrollForm = reactive({
  activityId: null,
  reason: ''
})

const statusOptions = [
  { label: '报名中', value: 'RECRUITING' },
  { label: '进行中', value: 'IN_PROGRESS' },
  { label: '已完成', value: 'COMPLETED' }
]

const categoryOptions = [
  { label: '环保公益', value: '环保公益' },
  { label: '敬老助老', value: '敬老助老' },
  { label: '教育文化', value: '教育文化' },
  { label: '扶贫济困', value: '扶贫济困' },
  { label: '文明倡导', value: '文明倡导' }
]

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

const loadActivities = async () => {
  try {
    const res = await getActivityList({
      page: pagination.page,
      size: pagination.pageSize,
      status: filters.status,
      category: filters.category
    })
    activities.value = res.data.records || []
    pagination.pageCount = res.data.pages || 1
  } catch (error) {
    console.error('加载活动失败:', error)
  }
}

const handlePageSizeChange = (pageSize) => {
  pagination.pageSize = pageSize
  pagination.page = 1
  loadActivities()
}

const handleEnroll = (activity) => {
  enrollForm.activityId = activity.id
  enrollForm.reason = ''
  enrollModalVisible.value = true
}

const confirmEnroll = async () => {
  try {
    await enrollActivity(enrollForm.activityId, {
      userId: userStore.userId,
      reason: enrollForm.reason
    })
    window.$message?.success('报名成功')
    enrollModalVisible.value = false
    loadActivities()
  } catch (error) {
    console.error('报名失败:', error)
  }
}

onMounted(() => {
  loadActivities()
})
</script>

